/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-24 09:12:38
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-27 17:44:37
 * @FilePath: \vue3_nuxt_demo\server\api\note\index.get.ts
 * @Description: 获取用户文章接口
 */
import Joi from 'joi';
import { responseJson, getLoginUid } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则获取用户的文章
 */

export default defineEventHandler(
  async (event) => {

    //获取用户id，判断是否登录
    const uid = getLoginUid(event);

    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }
    // 获取请求体
    const query = await getQuery(event);
    
    // 数据校验
    const schema = Joi.object({
      pageNo: Joi.number().min(1).required(),
      pageSize: Joi.number().min(10).required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(query);
    }
    catch (error) {
      return responseJson(400,  {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();

    try {

      const {pageNo = 1, pageSize = 10} = query as any;

      // 限制条数
      const limit = pageSize;

      // 开始位置
      const offset = (pageNo - 1) * pageSize;

      // 用户文章查询
      const [rows] = await con.query(
        'SELECT * FROM `notes` WHERE `uid`=? ORDER BY `id` DESC LIMIT ? OFFSET ?',
        [uid, Number(limit), offset]
      );
      
      return  responseJson(200,{
        success: true,
        msg: '获取成功',
        data: rows
      });

    }
    catch (error){
      // 设置响应状态码
      setResponseStatus(event,500);
      // 响应
      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }
  }
);